package com.lyf.controll;

import cn.hutool.json.JSONObject;

import com.lyf.pojo.Document;
import com.lyf.pojo.User;
import com.lyf.result.Code;
import com.lyf.result.Result;
import com.lyf.service.DocumentService;
import com.lyf.service.UserService;
import com.lyf.service.impl.DocumentServiceImpl;
import com.lyf.service.impl.UserServiceImpl;
import com.lyf.utils.PageModel;
import com.lyf.utils.ResponseResult;
import com.lyf.utils.Upload;
import com.lyf.vo.CountVoByName;
import redis.clients.jedis.Jedis;

import javax.print.Doc;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "DocumentControll" ,urlPatterns = {"/document/upload","/document/save","/document/download","/document/delete","/document/fileCount",
            "/document/selectById","/document/queryDocuments"})
public class DocumentControll extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DocumentService documentService = new DocumentServiceImpl();
        UserService userService = new UserServiceImpl();
        String servletPath = req.getServletPath();
        System.out.println("请求路径："+servletPath);
//        Document uploadFile = null;
        if(servletPath.equals("/document/upload")){
            Upload.uploadFile(req, resp);
        }else if(servletPath.equals("/document/save")){
            String title = req.getParameter("title");
            String remark = req.getParameter("remark");
            String id = req.getParameter("id");

            User user = userService.selectById(Integer.parseInt(id));

            // 获取当前时间
            LocalDateTime createdate = LocalDateTime.now();

            Jedis jedis = new Jedis("127.0.0.1",6379);
            jedis.auth("123456");
            String filename = jedis.get("filename");
            String filetype = jedis.get("filetype");

            Document document = new Document();
            document.setFileName(filename);
            document.setFiletype(filetype);
            document.setTitle(title);
            document.setRemark(remark);
            document.setUser(user);
            document.setUserId(Integer.parseInt(id));
            document.setCreateDate(createdate);

            documentService.uploadFile(document);

            Result result = new Result(Code.OK,null,"上传成功！");

            ResponseResult.sendResult(resp,result);
        }
        else if(servletPath.equals("/document/download")){
            //1.获取下载链接的fileName
            String fileName = req.getParameter("filename");
            //2.设置响应头
            resp.setHeader("content-disposition","attachment;filename=" + fileName);
            //3.下载文件
            File file = new File("D:\\粤嵌Java\\第二阶段\\项目\\前端\\hrm\\src\\files");
            try(InputStream is = new FileInputStream(file+File.separator+fileName);
                OutputStream os = resp.getOutputStream();
            ){
                int len = 0;
                byte[] b = new byte[1024];
                //循环读写
                while((len = is.read(b)) >0){
                    os.write(b,0,len);
                }

                Result result = new Result(Code.OK,null,"下载成功！");
                Map<String,Object> map = new HashMap<>();
                JSONObject jo = new JSONObject();
                map.put("result",result);
                jo.putAll(map);
                resp.getWriter().println(jo.toString());//响应到浏览器
            }catch (IOException e){
                e.printStackTrace();
            }
        }else if(servletPath.equals("/document/delete")){
            String id = req.getParameter("id");
            Document document = documentService.selectById(Integer.parseInt(id));
            documentService.delete(Integer.parseInt(id));

            //读取d盘的文件夹
            File file = new File("D:\\粤嵌Java\\第二阶段\\项目\\前端\\hrm\\src\\files");

            File[] files = file.listFiles();
            //3.循环写超链接
            for(File f:files){
                //加判断
                if(f.isFile()){
                    if(f.getName().equals(document.getFileName())){
                        boolean deleted = f.delete();
                        if (deleted) {
                            Result result = new Result(Code.OK,null,"文件删除成功！");
                            ResponseResult.sendResult(resp,result);
                        } else {
                            Result result = new Result(Code.Fail,null,"文件删除失败！");
                            ResponseResult.sendResult(resp,result);
                        }
                    }
                }
            }
        }else if(servletPath.equals("/document/fileCount")){

            List<CountVoByName> countVoByNames = documentService.selectFileCount();

            for (CountVoByName countVoByName : countVoByNames) {
                if(countVoByName.getName().equals("image/png")){
                    countVoByName.setName("PNG");
                }
                if(countVoByName.getName().equals("image/jpeg")){
                    countVoByName.setName("JPG");
                }
                if(countVoByName.getName().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")){
                    countVoByName.setName("XLSX");
                }
                if(countVoByName.getName().equals("application/vnd.ms-excel")){
                    countVoByName.setName("XLS");
                }
                if(countVoByName.getName().equals("application/x-zip-compressed")){
                    countVoByName.setName("ZIP");
                }
                if(countVoByName.getName().equals("application/pdf")){
                    countVoByName.setName("PDF");
                }
                if(countVoByName.getName().equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")){
                    countVoByName.setName("PPTX");
                }
                if(countVoByName.getName().equals("text/plain")){
                    countVoByName.setName("TXT");
                }
                if(countVoByName.getName().equals("image/svg+xml")){
                    countVoByName.setName("SVG");
                }
                if(countVoByName.getName().equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")){
                    countVoByName.setName("DOCX");
                }
                if(countVoByName.getName().equals("application/octet-stream")){
                    countVoByName.setName("编程文件");
                }
                if(countVoByName.getName().equals("video/mp4")){
                    countVoByName.setName("MP4");
                }
                if(countVoByName.getName().equals("video/mp3")){
                    countVoByName.setName("MP3");
                }
                if(countVoByName.getName().equals("application/msword")){
                    countVoByName.setName("DOC");
                }
            }

            Result result = new Result(Code.OK,countVoByNames,"查询成功！");
            ResponseResult.sendResult(resp,result);
        }else if(servletPath.equals("/document/selectById")){
            String id = req.getParameter("id");

            Document document = documentService.selectById(Integer.parseInt(id));

            Result result = new Result(Code.OK,document,"查询成功！");
            ResponseResult.sendResult(resp,result);
        }else if(servletPath.equals("/document/queryDocuments")){
            //获得当前页码
            String pageIndex = req.getParameter("pageNum");
            //获取每页显示条数
            String pageSize = req.getParameter("pageSize");

            //当前页码
            int pageNum = Integer.parseInt(pageIndex);
            //每页显示条数
            int pageSize2 = Integer.parseInt(pageSize);

            //设置到PageModel
            PageModel model = new PageModel();
            model.setPageIndex(pageNum);
            model.setPageSize(pageSize2);

            //获取查询条件
            String title = req.getParameter("title");
            String filetype = req.getParameter("filetype");

            //查询用户列表
            List<Document> documents = null;
            Document document = new Document();

            document.setTitle(title);
            document.setFiletype(filetype);

            //总记录数
            int count = documentService.getTotalDocumentCount(document);
            model.setTotalRecoreSum(count);
            documents = documentService.queryDocument(document,model);

            for (Document document1 : documents) {
                User user = userService.selectById(document1.getUserId());
                document1.setUser(user);
            }

            Map<String,Object> map = new HashMap<>();
            map.put("model",model);
            System.out.println("model:"+model);
            map.put("data",documents);

            JSONObject jo = new JSONObject();
            jo.putAll(map);
            resp.getWriter().println(jo.toString());//响应到浏览器
        }
    }
}
